package com.android.clinic.app.ui.personal;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.clinic.app.ClinicApplication;
import com.android.clinic.app.R;
import com.android.clinic.app.base.BaseActivity;
import com.android.clinic.app.entity.DuePriceInfo;
import com.android.clinic.app.http.HttpClient;
import com.android.clinic.app.http.base.BaseObserver;
import com.android.clinic.app.http.utils.RxObservableUtils;
import com.android.clinic.app.ui.pay.ClinicAliPay;
import com.android.clinic.app.ui.pay.ClinicWeChatPay;
import com.android.clinic.app.ui.pay.OnWXPayCallbackListener;
import com.android.clinic.app.ui.pay.PayUtils;
import com.android.clinic.app.utils.AppManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.List;

/**
 * 续费会员卡
 * Created by cheng on 2018/9/28.
 */
public class RenewalFeeMemberActivity extends BaseActivity {

    private DecimalFormat decimalFormat = new DecimalFormat("0.00");
    private List<DuePriceInfo> listPriceInfo;

    private TextView tvPrice, tvRealPrice;
    private ImageView ivWxPay, ivAliPay;
    private boolean isPayType = true;
    private String realPrice = "";
    private String payTitle = "爱帮诊服务费";

    private LinearLayout layRenewalFeeTime;
    private ImageView tempImageView;

    private String id = "";
    private int alwaysFree, days = 0;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_renewal_fee_member;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        setTitleBarTitle("续费会员卡");
        setTitleBarLeftResource(R.drawable.icon_back);
        tvPrice = (TextView) findViewById(R.id.tv_price);
        tvRealPrice = (TextView) findViewById(R.id.tv_real_price);
        layRenewalFeeTime = (LinearLayout) findViewById(R.id.layout_renewal_fee_time);
        ivWxPay = (ImageView) findViewById(R.id.iv_wx_pay);
        ivAliPay = (ImageView) findViewById(R.id.iv_ali_pay);
        ivWxPay.setSelected(isPayType);
    }

    @Override
    protected void loadData() {
        super.loadData();
        HttpClient.getHttpService().getDuePrice()
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<List<DuePriceInfo>>() {
                    @Override
                    public void onSuccess(List<DuePriceInfo> duePriceInfo) {
                        setRenewalFee(duePriceInfo);
                        listPriceInfo = duePriceInfo;
                        id = listPriceInfo.get(0).getId();
                        //0：永久免费用户 1：续费用户
                        alwaysFree = 1;
                        days = listPriceInfo.get(0).getDuration() * 365;
                        realPrice = decimalFormat.format(Double.valueOf(listPriceInfo.get(0).getPrice()));
                        tvPrice.setText(getString(R.string.price, realPrice));
                        tvRealPrice.setText(getString(R.string.real_price, realPrice));
                    }

                    @Override
                    public void onFailure(String message) {

                    }
                });
    }

    private void setRenewalFee(List<DuePriceInfo> duePriceInfo) {
        for (int i = 0, renewalFeeSize = duePriceInfo.size(); i < renewalFeeSize; i++) {
            View renewalFeeView = LayoutInflater.from(RenewalFeeMemberActivity.this)
                    .inflate(R.layout.item_renewal_fee_time, null);
            TextView tvRemark = (TextView) renewalFeeView.findViewById(R.id.tv_remark);
            ImageView ivRenewalFee = (ImageView) renewalFeeView.findViewById(R.id.iv_renewal_fee);
            LinearLayout layRenewalPrice = (LinearLayout) renewalFeeView.findViewById(R.id.layout_renewal_fee_price);
            layRenewalPrice.setTag(i);
            if(i == 0){
                tempImageView = ivRenewalFee;
                ivRenewalFee.setSelected(true);
            }
            View renewalFeeLine = renewalFeeView.findViewById(R.id.renewal_fee_view);
            tvRemark.setText(duePriceInfo.get(i).getRemark());
            renewalFeeLine.setVisibility(i == renewalFeeSize - 1 ? View.GONE : View.VISIBLE);
            layRenewalPrice.setOnClickListener(v -> {
                int position = (int) v.getTag();
                if(tempImageView != null){
                    tempImageView.setSelected(false);
                }
                tempImageView = ivRenewalFee;
                ivRenewalFee.setSelected(true);
                id = listPriceInfo.get(position).getId();
                //0：永久免费用户 1：续费用户
                alwaysFree = listPriceInfo.get(position).getDuration() < 0 ? 0 : 1;
                days = listPriceInfo.get(position).getDuration() * 365;

                realPrice = decimalFormat.format(Double.valueOf(listPriceInfo.get(position).getPrice()));
                tvPrice.setText(getString(R.string.price,  realPrice));
                tvRealPrice.setText(getString(R.string.real_price, realPrice));
            });
            layRenewalFeeTime.addView(renewalFeeView);
        }
    }

    @Override
    protected void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()){
            // 微信支付
            case R.id.layout_wx_pay:
                isPayType = true;
                ivWxPay.setSelected(true);
                ivAliPay.setSelected(false);
                break;
            // 支付宝支付
            case R.id.layout_ali_pay:
                isPayType = false;
                ivWxPay.setSelected(false);
                ivAliPay.setSelected(true);
                break;
            // 去支付
            case R.id.tv_pay:
                if (isPayType) {
                    paymentOrderWithWeChat();
                } else {
                    paymentOrderWithALi();
                }
                break;
        }
    }

    /**
     * 续费会员
     */
    private void rechargeVip() {
        HttpClient.getHttpService().rechargeVip(id, alwaysFree, days)
                .compose(RxObservableUtils.applySchedulers(loading, "请求中..."))
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        showToast("支付成功!");
                        gotoLoginActivity();
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast("支付失败, 请联系线上客服!");
                        finish();
                    }
                });
    }

    /**
     * 获取支付宝支付订单
     */
    private void paymentOrderWithALi() {
        HttpClient.getHttpService().aliPay("爱帮诊支付", payTitle, realPrice,
                ClinicApplication.getUserInfo().getId())
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject json = jsonObject.getJSONObject("element");
                            ClinicAliPay clinicAliPay = new ClinicAliPay(RenewalFeeMemberActivity.this);
                            clinicAliPay.aliPay(json.getString("body"));
                            //支付宝支付状态
                            clinicAliPay.setOnPaySuccessListener(new ClinicAliPay.OnPaySuccessListener() {
                                @Override
                                public void onSuccess() {
                                    rechargeVip();
                                }

                                @Override
                                public void onFailure() {
                                    showToast("支付失败, 请联系线上客服!");
                                    finish();
                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }

    /**
     * 获取微信支付订单
     */
    private void paymentOrderWithWeChat() {
        HttpClient.getHttpService().weChatPay(payTitle, realPrice,
                ClinicApplication.getUserInfo().getId())
                .compose(this.bindToLifecycle())
                .compose(RxObservableUtils.applySchedulers())
                .subscribe(new BaseObserver<String>() {
                    @Override
                    public void onSuccess(String s) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            JSONObject json = jsonObject.getJSONObject("element");
                            JSONObject data = json.getJSONObject("body");
                            ClinicWeChatPay weChatPay = new ClinicWeChatPay(RenewalFeeMemberActivity.this, data);
                            weChatPay.initPay();
                            PayUtils.getInstance().setCallBackListener(new OnWXPayCallbackListener() {
                                @Override
                                public void onSuccess() {
                                    rechargeVip();
                                }

                                @Override
                                public void onFailure(int errCode) {
                                    showToast("支付失败, 请联系线上客服!");
                                    finish();
                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(String message) {
                        showToast(message);
                    }
                });
    }

    /**
     * 续费成功之后, 从新登录
     */
    private void gotoLoginActivity() {
        ClinicApplication.saveUserInfo(null);
        startActivity(new Intent(RenewalFeeMemberActivity.this, LoginActivity.class));
        AppManager.getAppManager().finishAllActivity();
    }

}
